import React, { useEffect, useState } from 'react'
import { Button, Popconfirm, Table, Tag, Popover, Switch } from 'antd';
import axios from 'axios';





export default function RightList() {

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '权限名称',
      dataIndex: 'title',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render: (key) => {
        return <Tag color='cyan'>{key}</Tag>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Popconfirm
            title="删除"
            description="你确定要删除吗"
            onConfirm={() => deleteItem(item)}
            okText="确定"
            cancelText="取消"
          >
            <Button type='primary' danger >删除</Button>
          </Popconfirm>

          <Popover trigger={item.pagepermisson === undefined ? '' : 'click'} content={<Switch checked={item.pagepermisson ? true : ''} onChange={() => changeSwitch(item)}></Switch>} title="配置项">
            <Button type='primary' disabled={item.pagepermisson === undefined ? true : ''}>编辑</Button>
          </Popover>

        </div>
      }

    }
  ];


  const [dataSource, setDataSource] = useState([])
  // 初始化数据
  useEffect(() => {
    axios.get('/rights?_embed=children').then(res => {
      // console.log(res)
      res.data.forEach(item => {
        if (item.children.length === 0) {
          item.children = ''
        }
      })
      setDataSource(res.data)
    })
  }, [])

  // 删除
  function deleteItem(item) {
    // 当前页面同步+后端同步
    if (item.grade === 1) {
      setDataSource(dataSource.filter(i => i.id !== item.id))
      axios.delete(`/rights/${item.id}`)
    } else {
      // 删除二级
      // console.log(item)
      let list = dataSource.filter(data => data.id === item.rightId)
      list[0].children = list[0].children.filter(data => data.id !== item.id)
      // console.log(list)
      setDataSource([...dataSource])
      axios.delete(`/children/${item.id}`)
    }
  }

  // 改变开关
  function changeSwitch(item) {
    // 直接改变item会直接影响dataSource
    item.pagepermisson = item.pagepermisson === 1 ? 0 : 1
    setDataSource([...dataSource])
    // 改变第一级
    if (item.grade === 1) {
      axios.patch(`/rights/${item.id}`, {
        pagepermisson: item.pagepermisson
      })
    } else {
      axios.patch(`/children/${item.id}`, {
        pagepermisson: item.pagepermisson
      })
    }
  }


  return (
    <Table dataSource={dataSource} columns={columns} pagination={{ pageSize: 5 }} />
  )
}
